package com.cst.words.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cst.words.mapper.UserMapper;
import com.cst.words.pojo.User;
import com.cst.words.util.HttpRequest;
import com.cst.words.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : CST
 */
@RestController
@RequestMapping("/wx")
@Slf4j
public class WxController {
    @Autowired
    private UserMapper userMapper;


    private String openid;

    @GetMapping("/login")
    public Object findOpenIdAndLogin(@RequestParam String code) {
        // return code;
        String appid = "wx405802c575134592";
        String secret = "3530354184fd35014523ee9294d77521";
        // 授权（必填）
        String grant_type = "authorization_code";
        String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=" + grant_type;
        // 发送请求
        HttpRequest HttpRequest = null;
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // 解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        openid = (String) json.get("openid");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, openid);
        User user = this.userMapper.selectOne(queryWrapper);
        //没有这个用户数据就插入新的用户数据
        if (null == this.userMapper.isExist(openid)) {
            user = new User();
            log.info(openid + "的用户的信息是" + user);
            user.setOpenid(openid);
            userMapper.insertInfo(user);
        }else
        // 有用户数据
        // 生成jwt令牌并返回，但是怎么返回两个呢
        //全部放到map里面？Y
        if (user != null){
            Map<String, Object> map = new HashMap<>();
            map.put("id",user.getId());
            map.put("openid",user.getOpenid());
            map.put("username",user.getUsername());
            map.put("avatar",user.getAvatar());
            String jwt = JwtUtils.generateJwt(map);
            return jwt;//只保存openid在更新和建议时候调用，不要影响用户信息的返回
        }

        return userMapper.selectAll(user);
    }

}
